<template>
  <view class="publish-container mo-container">
    <view class="header bg-white">
      <view class="container uni-py-4">
        <view class="d-flex justify-content-between align-items-center uni-px-3">
          <view class="section-title">
            <text class="bi bi-shop me-2 text-primary-new"></text>

            <text class="animate__animated animate__fadeInDown uni-error fs-6">发布商品</text>
          </view>
        </view>
      </view>
    </view>

    <view class="form-section">
      <uni-forms ref="productForm" :model="productForm" :rules="rules">
        <!-- 商品名称 -->
        <uni-forms-item label="商品名称" name="name">
          <uni-easyinput
            v-model="productForm.name"
            placeholder="请输入商品名称"
          />
        </uni-forms-item>

        <!-- 商品描述 -->
        <uni-forms-item label="商品描述" name="description">
          <uni-easyinput
            v-model="productForm.description"
            type="textarea"
            placeholder="请输入商品描述"
          />
        </uni-forms-item>

        <!-- 商品价格 -->
        <uni-forms-item label="商品价格" name="price">
          <uni-easyinput
            v-model="productForm.price"
            type="number"
            placeholder="请输入商品价格"
          />
        </uni-forms-item>

        <!-- 商品图片 -->
        <uni-forms-item label="商品图片" name="image">
          <view class="upload-section">
            <view class="upload-preview" v-if="productForm.image">
              <image :src="productForm.image" mode="aspectFit" class="preview-image" />
              <text class="remove-btn" @tap="removeImage">×</text>
            </view>
            <view v-else class="upload-btn" @tap="chooseImage">
              <text class="bi bi-plus-circle"></text>
              <text>上传图片</text>
            </view>
          </view>
        </uni-forms-item>

        <!-- 商品分类 -->
        <uni-forms-item label="商品分类" name="category">
          <view class="category-select">
            <picker @change="onCategoryChange" :value="categoryIndex" :range="categoryOptions">
              <view class="picker-view">
                <text>{{ categoryOptions[categoryIndex] || '请选择商品分类' }}</text>
                <text class="bi bi-chevron-down"></text>
              </view>
            </picker>
          </view>
        </uni-forms-item>

        <!-- 商品库存 -->
        <uni-forms-item label="商品库存" name="stock">
          <uni-easyinput
            v-model="productForm.stock"
            type="number"
            placeholder="请输入商品库存"
          />
        </uni-forms-item>

        <!-- 是否新品 -->
        <uni-forms-item label="是否新品" name="isNew">
          <switch
            :checked="productForm.isNew"
            @change="(e) => (productForm.isNew = e.detail.value)"
            color="#6c8380"
          />
        </uni-forms-item>

        <!-- 提交按钮 -->
        <view class="submit-section">
          <button class="submit-btn" type="primary" @tap="submitForm">发布商品</button>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useUserStore } from "@/stores/userStore";

const userStore = useUserStore();
const productForm = reactive({
  name: "",
  description: "",
  price: "",
  image: "",
  category: "stationery", // 默认类别
  stock: "100",
  isNew: true
});

const rules = {
  name: {
    rules: [
      { required: true, errorMessage: "请输入商品名称" }
    ]
  },
  description: {
    rules: [
      { required: true, errorMessage: "请输入商品描述" }
    ]
  },
  price: {
    rules: [
      { required: true, errorMessage: "请输入商品价格" },
      { pattern: /^[1-9]\d*(\.\d{1,2})?$/, errorMessage: "价格格式不正确" }
    ]
  },
  image: {
    rules: [
      { required: true, errorMessage: "请上传商品图片" }
    ]
  },
  category: {
    rules: [
      { required: true, errorMessage: "请选择商品分类" }
    ]
  },
  stock: {
    rules: [
      { required: true, errorMessage: "请输入商品库存" },
      { pattern: /^[1-9]\d*$/, errorMessage: "库存必须为正整数" }
    ]
  }
};

// 商品分类选项
const categoryOptions = [
  "文具",
  "饰品",
  "服饰",
  "生活",
  "收藏"
];

// 类别映射表
const categoryMap = {
  "文具": "stationery",
  "饰品": "accessories",
  "服饰": "clothing",
  "生活": "daily",
  "收藏": "collection"
};

const categoryIndex = ref(0);

// 监听分类选择变化
const onCategoryChange = (e) => {
  categoryIndex.value = e.detail.value;
  productForm.category = categoryMap[categoryOptions[categoryIndex.value]];
};

// 表单对象
const productForm$ = ref(null);

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      uploadImage(tempFilePath);
    }
  });
};

// 上传图片
const uploadImage = (filePath) => {
  uni.showLoading({ title: '上传中...' });
  
  // 这里使用示例数据，实际项目需要替换为真实的图片上传逻辑
  setTimeout(() => {
    productForm.image = filePath;
    uni.hideLoading();
  }, 1000);
  
  // 实际项目中使用uniCloud上传接口
  // uniCloud.uploadFile({
  //   filePath,
  //   cloudPath: `product/${Date.now()}-${Math.random().toString(36).slice(-6)}.${filePath.split('.').pop()}`,
  //   success: (res) => {
  //     productForm.image = res.fileID;
  //     uni.hideLoading();
  //   },
  //   fail: (err) => {
  //     uni.hideLoading();
  //     uni.showToast({
  //       title: '图片上传失败',
  //       icon: 'none'
  //     });
  //   }
  // });
};

// 移除图片
const removeImage = () => {
  productForm.image = "";
};

// 提交表单
const submitForm = async () => {
  // 校验表单
  try {
    const validateResult = await productForm$.value.validate();
    
    // 检查用户角色
    if (userStore.userInfo.role !== 2) {
      uni.showToast({
        title: '只有商家才能发布商品',
        icon: 'none'
      });
      return;
    }
    
    uni.showLoading({ title: '发布中...' });
    
    // 调用云函数发布商品
    uniCloud.callFunction({
      name: 'product',
      data: {
        action: 'addProduct',
        data: {
          ...productForm,
          price: Number(productForm.price),
          stock: Number(productForm.stock),
          userId: userStore.userInfo._id, // 关联用户ID
          merchantId: userStore.userInfo._id, // 商家ID
          merchantName: userStore.userInfo.nickname || userStore.userInfo.username,
          createTime: Date.now()
        }
      },
      success: (res) => {
        const { code, message, data } = res.result;
        if (code === 0) {
          uni.showToast({
            title: '发布成功',
            icon: 'success'
          });
          
          // 清空表单
          resetForm();
          
          // 延迟跳转回列表页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: message || '发布失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '发布失败，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        uni.hideLoading();
      }
    });
  } catch (e) {
    console.log('表单校验失败', e);
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(productForm, {
    name: "",
    description: "",
    price: "",
    image: "",
    category: "stationery",
    stock: "100",
    isNew: true
  });
  categoryIndex.value = 0;
};

// 组件挂载时检查用户角色
onMounted(() => {
  if (!userStore.userInfo || userStore.userInfo.role !== 2) {
    uni.showToast({
      title: '只有商家才能访问此页面',
      icon: 'none'
    });
    
    // 延迟跳转回首页
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style lang="scss" scoped>
.publish-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 100rpx;
}

.header {
  border-bottom: 1px solid #eee;
}

.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  margin: 30rpx;
  padding: 30rpx;
}

.upload-section {
  display: flex;
  justify-content: center;
  margin: 20rpx 0;
}

.upload-btn {
  width: 200rpx;
  height: 200rpx;
  border: 1px dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
}

.upload-preview {
  position: relative;
  width: 200rpx;
  height: 200rpx;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.remove-btn {
  position: absolute;
  top: -20rpx;
  right: -20rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #ff4d4f;
  color: #fff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
}

.category-select {
  width: 100%;
}

.picker-view {
  height: 70rpx;
  line-height: 70rpx;
  padding: 0 20rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.submit-section {
  margin-top: 50rpx;
  padding: 0 30rpx;
}

.submit-btn {
  background-color: var(--td-brand-color);
  color: #fff;
}
</style> 